<template>
  <PageWrapper v-loading="loadingRef" content-full-height fixed-height dense>
    <AdVxeTable @register="registerTable">
      <template #tools>
        <Authority value="Root.Mobile.Admin.App.Create">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />{{ t('common.addText') }}
          </a-button>
        </Authority>
      </template>

      <template #iconCol="{ row }">
        <TableImg :size="30" :simple-show="true" :show-badge="false" :img-list="[row?.Icon]" :fallback="logoImage" />
      </template>

      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Mobile.Admin.App.Delete', // 权限控制
              // ifShow: (_action) => {
              //   return row?.IsSystem !== true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              // },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
          :drop-down-actions="[
            {
              icon: 'clarity:details-line',
              label: t('common.detailText'),
              auth: 'Root.Mobile.Admin.App.Get', // 权限控制
              onClick: handleDetail.bind(null, row),
            },
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Mobile.Admin.App.UpdateSimple', // 权限控制
              onClick: handleEdit.bind(null, row),
            },
          ]"
        />
      </template>
    </AdVxeTable>

    <DetailModal @register="registerDetailModal" :after-submit-func="handleAfterDetailSubmit" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import type { AjaxResult } from '#/request';

  import { computed, ref } from 'vue';

  import { deleteApp, readAppSimple } from '@/api/mobile/admin/app';
  import { useModal } from '@/components/AdVxeModal';
  import { AdVxeTable, TableAction, TableImg, useAdVxeTable } from '@/components/AdVxeTable';
  import { Authority } from '@/components/Authority';
  import Icon from '@/components/Icon/Icon.vue';
  import { PageWrapper } from '@/components/Page';
  import { FormModeEnum } from '@/enums/formEnum';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { usePreferenceStore } from '@/store/modules/preference';

  import DetailModal from './detail.vue';
  import { columns } from './index.data';

  defineOptions({ name: 'MobAppPage' });

  const { t } = useI18n();
  const preferenceStore = usePreferenceStore();
  const { createMessage } = useMessage();

  const logoImage = computed(() => preferenceStore.getLogo);

  const loadingRef = ref(false);
  function openWrapLoading() {
    loadingRef.value = true;
  }
  function closeWrapLoading() {
    loadingRef.value = false;
  }

  const [registerTable, { reload }] = useAdVxeTable({
    id: 'ea_mobile_app_page',
    // 表标题呈现器
    title: t('mobile.route.app.listText'),
    // 表格数据接口请求对象
    api: readAppSimple,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'ea_mobile_app_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('mobile.route.app.title'),
    },
    // 表单列信息 AdColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    // 行选择设置
    // selection: 'checkbox',
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  const [registerDetailModal, detailModalMethods] = useModal();
  /** 处理新增 */
  async function handleCreate() {
    detailModalMethods.openModal(true, {
      formMode: FormModeEnum.Add,
      record: null,
    });
  }
  /** 处理查看详情 */
  async function handleDetail(record: any) {
    if (record && record.Id) {
      openWrapLoading();
      try {
        // TODO:详情表单的弹窗
        detailModalMethods.openModal(true, {
          formMode: FormModeEnum.ReadOnly,
          record,
        });
      } finally {
        closeWrapLoading();
      }
    }
  }
  /** 处理编辑 */
  async function handleEdit(record: any) {
    if (record && record.Id) {
      openWrapLoading();
      try {
        // TODO:详情表单的弹窗
        detailModalMethods.openModal(true, {
          formMode: FormModeEnum.Edit,
          record,
        });
      } finally {
        closeWrapLoading();
      }
    }
  }
  /** 处理删除 */
  async function handleDelete(record: any) {
    const result = await deleteApp([record.Id]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      await reload();
    }
  }

  /** 处理详情表单提交后回调，返回true关闭窗体 */
  async function handleAfterDetailSubmit(formMode: FormModeEnum, result?: AjaxResult | null, _record?: any) {
    if (result) {
      if (result?.Succeeded) {
        if (result?.Content) {
          createMessage.success(result.Content);
        } else {
          createMessage.success(t('common.successText'));
        }
        switch (formMode) {
          case FormModeEnum.Add:
          case FormModeEnum.Edit:
          case FormModeEnum.Delete:
            await reload();
            break;
        }
        return true;
      } else {
        return false;
      }
    }
    return true;
  }
</script>
